<?php
namespace app\model;



class w_input {
    static function bangding($system,$config,$fans) {
    global $_P, $_G;
    $recordid = intval($_P['recordid']);
    $sql = "SELECT * FROM " . tablename (t_record) . "
                                WHERE id = :id and (status > 0 or status=-2) ";
    $record = db_find($sql, array(":id"=>$recordid));
    $themeid = $record['themeid'];
    $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
    if(!(!$system['is_multiple_merchants'] || $config['showshop']==0 || ($system['is_multiple_merchants'] && $config['showshop']==$myworker['company']))){
        $myworker = "";
    }

        if (!empty($record['openid'])){
            if($record['openid'] == $_G['openid']){
                $result = array(
                    'msg' => '已绑定成功',
                );
                return $result;
            }else{
                return array('error' =>1 , 'msg' => "此定单已绑定微信:".$record['nickname'] );
            }
        }


        $sql = "SELECT id,username FROM " . tablename (t_record) . "
                                WHERE uid = :uid and (status > 0) and id <> '" . $record['id']."'";
        $isbangding = db_select($sql, array(":uid"=>$_G['member']['uid']));
        $isbukuan = $config['yukuan']>0 && (TIMESTAMP>$config['yukuantime'])?true:false;
        if ($config['wuxian']==0 && (count($isbangding)>1 && $isbukuan || count($isbangding)==1 && !$isbukuan)){
            $dingdangid = $isbangding[0]['id'] + 9000;
            wxapp_result (1 , "此微信已绑定定单:".$dingdangid ."-".$isbangding[0]['username'] );
        }

        if (empty($myworker)) {
            if ($fans['nickname']=='微信用户'){
                return array('error' =>1 , 'msg' => "请进入活动首页，授权登录后才可绑定");
            }
            $data = array(
                'openid'   => $_G['openid'],
                'uid'      => $_G['member']['uid'],
                'nickname' => $fans['nickname'],
                'avatar'   => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
//                'pid'      => $recordid,
                'beizhu' => $record['beizhu'] . date('Y-m-d H:i:s') . ' 绑定微信：' . $fans['nickname'] . '<br>',
            );
            $r = db_update(t_record,$data,array("id"=>$record['id']));



            //绑定后调用微信支付回调
            $sql = "SELECT * FROM " . tablename (t_record) . "
                                WHERE id = :id and (status > 0 or status=-2) ";
            $record = db_find($sql, array(":id"=>$recordid));

            $data = array(
                'username'   => $record['username'],
                'mobile'   => $record['mobile'],
            );
            db_update(t_fans,$data,array("uid"=>$record['uid']));

            $theme = Theme::getThemeById($themeid);
            Common::pay($system,$theme,$config,$record,$recordid,$themeid,$record['fee']);

            if(!empty($r) && $system['iskoi']!=1){
                $result = array(
                    'msg' => '绑定成功',
                );
                return $result;
            }elseif(!empty($r)){
                db_update(t_fans,array('workerid'=>$record['workerid']),array("uid"=>$_G['member']['uid']));
                $config =   Theme::getConfig($themeid);
                $tip_text='';
                if (!empty($config['lz_game_img']) && !empty($config['five_themeid'])){
                    $config2 = Theme::getConfig($config['five_themeid']);
                    Koi::checkInFiveLtTime($config['five_themeid'],$_G['member']['uid'],$config2);
                    $tip_text ='，获得五连抽';
                }

                $result = array(
                    'msg' => $themeid.'five' .$config['five_themeid']. '绑定成功'.$tip_text,
                );
                return $result;
            }else{
                return array('error' =>1 , 'msg' => "保存失败请重试" );
            }
        }else{
            return array('error' =>1 , 'msg' => "只有非员工的微信才可以扫码绑定" );
        }

}

static function formatConfigShops($config) {
    //多选处理
    if (in_array($config['shopstype'],[0,3,4]) && $config['shops'] && $config['options']) {
//        $options = array_merge($config['gudingoptions'],$config['options']);
        $options=[];
        $selectedFee=0;
        if (empty($record['option']) && !empty($config['gudingoptions'])){
            $record['option'] = implode("|",$config['gudingoptions']);
        }

        if (!empty($config['gudingoptions'])) {
            foreach ($config['gudingoptions'] as $index => $row) {
                $options[]=array(
                    'price'=>$config['shops_price_guding'][$index],
                    'name'=>$row,
                );
            }
        }else{
            $config['gudingoptions'] = array();
        }
        if (!empty($config['options'])) {
            foreach ($config['options'] as $index => $row) {
                $options[]=array(
                    'price'=>$config['shops_price'][$index],
                    'name'=>$row,
                );
            }
        }
        $selectedNumber =0;
        $config['selectedArr']=array();
        if (!empty($record['option'])){
            $record['option']  = $record['option'] ."|";
        }
        foreach ($options as $index => $row) {
            $config['selectedArr'][$index]['price']=$row['price'];
            $config['selectedArr'][$index]['isguding']=false;
            if(strpos("||".$record['option'], "|".$row['name'] . "|") || in_array($row['name'],$config['gudingoptions'])){
                $config['selectedArr'][$index]['checked']=true;
                $config['selectedArr'][$index]['name']=$row['name'];
                if (in_array($row['name'],$config['gudingoptions'])){
                    $config['selectedArr'][$index]['isguding']=true;
                }
                $selectedFee+=$row['price'];
                $selectedNumber++;
            }else{
                $config['selectedArr'][$index]['checked']=false;
                $config['selectedArr'][$index]['name']=$row['name'];
            }
        }
    }
//    预售补款文本5多选分类处理
//    if (in_array($config['presale']['shopstype'],[0,3,4]) && $config['presale']['shops'] && $config['presale']['options']){
//        $options=[];
//        $selectedFee=0;
//        if (empty($record['option']) && !empty($config['presale']['gudingoptions'])){
//            $record['option'] = implode("|",$config['presale']['gudingoptions']);
//        }
//
//        if (!empty($config['presale']['gudingoptions'])) {
//            foreach ($config['presale']['gudingoptions'] as $index => $row) {
//                $options[]=array(
//                    'price'=>$config['presale_shops_price_guding'][$index],
//                    'name'=>$row,
//                );
//            }
//        }else{
//            $config['presale']['gudingoptions'] = array();
//        }
//        if (!empty($config['presale']['options'])) {
//            foreach ($config['presale']['options'] as $index => $row) {
//                $options[]=array(
//                    'price'=>$config['presale_shops_price'][$index],
//                    'name'=>$row,
//                );
//            }
//        }
//        $selectedNumber =0;
//        $config['selectedArr']=array();
//        if (!empty($record['option'])){
//            $record['option']  = $record['option'] ."|";
//        }
//        foreach ($options as $index => $row) {
//            $config['selectedArr'][$index]['price']=$row['price'];
//            $config['selectedArr'][$index]['isguding']=false;
//            if(strpos("||".$record['option'], "|".$row['name'] . "|") || in_array($row['name'],$config['presale']['gudingoptions'])){
//                $config['selectedArr'][$index]['checked']=true;
//                $config['selectedArr'][$index]['name']=$row['name'];
//                if (in_array($row['name'],$config['presale']['gudingoptions'])){
//                    $config['selectedArr'][$index]['isguding']=true;
//                }
//                $selectedFee+=$row['price'];
//                $selectedNumber++;
//            }else{
//                $config['selectedArr'][$index]['checked']=false;
//                $config['selectedArr'][$index]['name']=$row['name'];
//            }
//        }
//    }
    $config['selectedNumber'] =$selectedNumber;
    $config['selectedFee'] =$selectedFee;
    return $config;
}
static function check_chongfu($config,$themeid,$username,$mobile) {
    $addtime = TIMESTAMP-120;
    $sql = "SELECT * FROM " . tablename (t_record) . "
                                WHERE themeid =:themeid and username = :username
                                        and mobile = :mobile and status=3 and addtime >" . $addtime . " ";
    $row = db_find($sql, array(":themeid"=>$themeid,":username"=>$username,":mobile"=>$mobile));

    if (!empty($row)) {
        $msg = "错误：客户“".$username."”在2分钟内录入过线下定单，若实际为多个定单请在2分钟以后再次录入";
    }
    if ($config['xianxia_chongfu']!=1){
        if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']){
            $yukuan = "and addtime >" . $config['yukuantime'];
        }
        $sql = "SELECT * FROM " . tablename (t_record) . "
                                WHERE themeid =:themeid and username = :username
                                        and mobile = :mobile and status>0 " . $yukuan ;
        $row = db_find($sql, array(":themeid"=>$themeid,":username"=>$username,":mobile"=>$mobile));
        if (!empty($row)) {
            if ($row['status']==1){
                $msg = "错误：客户“".$username."”已在线上付款，若实际为多个定单，请更换手机号或开启允许线下定单重复录入";
            }else{
                $msg = "错误：客户“".$username."”已录入过，若实际为多个定单，请更换手机号或开启允许线下定单重复录入";
            }
        }
    }
    return $msg;
}
static function input($system,$theme,$config,$myworker) {
    global $_P, $_G;
    $themeid = intval($_P['themeid']);
    $op = !empty($_P['op']) ? $_P['op'] : 'display';
    $recordid = intval($_P['recordid']);
    if ($op=="reset"){
        $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;
        $qrimg = Poster::CreateScene($system,$scene,$config,'Worker/pages/w_input/w_input');

        $data = array(
            'openid'   => "",
            'uid'      => "",
            'nickname' => '未绑定客户微信',
            'avatar'   => $qrimg,
        );
        if (!empty($recordid)){
            db_update(t_record,$data,array("id"=>$recordid));
        }
        $op="getinfo";
    }

    if (!empty($recordid)){
        $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                    WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $recordid));
        $record['shops']=$record['option'];
    }

    if ($op=='display' || $op=="getinfo") {
        if ($_P['renshu']==1){
            $config['form2'] = self::formatConfigShops($config['form2']);
            $confignew = $config['form2'];
        }elseif ($_P['renshu']==2){
            $config['form3'] = self::formatConfigShops($config['form3']);
            $confignew = $config['form3'];
        }else{
            $config = self::formatConfigShops($config);
            if ($config['address'] == '盲盒礼品' && $_G['app_web_wxapp'] == 'mobile') {
                    $config['address'] = '';
                }
                $confignew = array(
                'is_show_service' => $config['is_show_service'],
                'shopstype' => $config['shopstype'],
                'shops' => $config['shops'],
                'options' => $config['options'],
                'addresstype' => $config['addresstype'],
                'address' => $config['address'],
                'addressoptions' => $config['addressoptions'],
                'formtwotype' => $config['formtwotype'],
                'formtwo' => $config['formtwo'],
                'formtwooptions' => $config['formtwooptions'],
                'selectedArr' => $config['selectedArr'],
                'nametext' => $config['nametext'],
                'mobiletext' => $config['mobiletext'],
                'datetimetype' => $config['datetimetype'],
                'datetime' => $config['datetime'],
                'addinfotype' => $config['addinfotype'],
                'addinfo' => $config['addinfo'],
                'shopstype' => $config['shopstype'],
                'shopsmax' => $config['shopsmax'],
                'shopsmin' => $config['shopsmin'],
                'selectedNumber' => $config['selectedNumber'],
                'selectedFee' => $config['selectedFee'],
            );
        }
        $confignew['selecet_pay'] =$system['selecet_pay'];
        $confignew['isedit'] = $myworker['level'];
        $confignew['is_member_points'] = $system['is_member_points'];
        $confignew['iseditorder'] = $config['iseditorder'];
        $confignew['isedit'] = $myworker['level'];
        $confignew['maxcountall'] = $config['maxcountall'];

        if($config['isxianxia']>0 || $myworker['level'] == 1){
            $confignew['isxianxia'] = true;
        }else{
            $confignew['isxianxia'] = false;
        }

        $feelist = array();
        if ($system['ruanjian']==5){
            if ($system['is_multiple_bargain'] == 1){
                foreach ($config['bargain_products'] as $key =>$item){
                    if (!empty($item['name']) && $item['joinprice'] != '0.00' && !empty($item['joinprice'])){
                        array_push($feelist, array('name'=>$item['name'] .'定金','fee'=>$item['joinprice'],'products_id'=>$key+1));
                    }elseif (!empty($item['name']) && $item['minprice'] != '0.00' && !empty($item['minprice'])){
                        array_push($feelist, array('name'=>$item['name'] .'最低价','fee'=>$item['minprice'],'products_id'=>$key+1));
                    }
                }
            }else{
                if ($config['bargain_joinprice'] != '0.00' && !empty($config['bargain_joinprice'])){
                    array_push($feelist, array('name'=>'定金','fee'=>$config['bargain_joinprice']));
                }elseif ($config['bargain_minprice'] != '0.00' && !empty($config['bargain_minprice'])){
                    array_push($feelist, array('name'=>'最低价','fee'=>$config['bargain_minprice']));
                }
                if ($config['bargain_buy'] != '0.00' && !empty($config['bargain_buy'])){
                    array_push($feelist, array('name'=>$config['bargain_buy_text'],'fee'=>$config['bargain_buy']));
                }
            }

        }else {
            if (!($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime'])) {
                if ($config['joinfee'] != '0.00' && !empty($config['joinfee'])) {
                    if ($system['jiage'] == 0) {
                        $payname = '定金';
                    } else {
                        $payname = $config['joinname'];
                    }
                    array_push($feelist, array('name' => $payname, 'fee' => $config['joinfee']));
                }
                if ($config['joinfee2'] != '0.00' && !empty($config['joinfee2'])) {
                    array_push($feelist, array('name' => $config['joinname2'], 'fee' => $config['joinfee2']));
                }
                if ($config['joinfee3'] != '0.00' && !empty($config['joinfee3'])) {
                    array_push($feelist, array('name' => $config['joinname3'], 'fee' => $config['joinfee3']));
                }
                if ($config['primeprice'] != '0.00' && !empty($config['primeprice'])) {
                    array_push($feelist, array('name' => '单买价', 'fee' => $config['primeprice']));
                }

                if ($config['groupprice'] != '0.00' && !empty($config['groupprice']) && ($_P['renshu'] == 0 || $system['bottom_jiage'] == 0)) {
                    array_push($feelist, array('name' => '拼团价', 'fee' => $config['groupprice']));
                }
                if ($config['groupprice2'] != '0.00' && !empty($config['groupprice2']) && $_P['renshu'] == 1) {
                    array_push($feelist, array('name' => '拼团价②', 'fee' => $config['groupprice2']));
                }
                if ($config['groupprice3'] != '0.00' && !empty($config['groupprice3']) && $_P['renshu'] == 2) {
                    array_push($feelist, array('name' => '拼团价③', 'fee' => $config['groupprice3']));
                }
            }else{
                if ($config['groupprice'] != '0.00' && !empty($config['groupprice']) && ($_P['renshu'] == 0 || $system['bottom_jiage'] == 0)) {
                    if ($system['bottom_jiage'] == 0){
                        $config['groupprice'] = $config['yukuan'];
                    }
                    $config['yukuan'] = $config['groupprice'];
                    array_push($feelist, array('name' => '全款', 'fee' => $config['groupprice']));
                }
                if ($config['groupprice2'] != '0.00' && !empty($config['groupprice2']) && $_P['renshu'] == 1) {
                    $config['yukuan'] = $config['groupprice2'];
                    array_push($feelist, array('name' => '全款②', 'fee' => $config['groupprice2']));
                }
                if ($config['groupprice3'] != '0.00' && !empty($config['groupprice3']) && $_P['renshu'] == 2) {
                    $config['yukuan'] = $config['groupprice3'];
                    array_push($feelist, array('name' => '全款③', 'fee' => $config['groupprice3']));
                }
                $fee_group = db_select("SELECT fee FROM " . tablename(t_record) ." where themeid ='{$themeid}' and status>0 and addtime<'{$config['yukuantime']}' group by fee");
                foreach ($fee_group as $item){
                    $tmp_fee = $config['yukuan'] - $item['fee'];
                    if ($tmp_fee>0){
                        array_push($feelist, array('name'=>'补差价','fee'=>$tmp_fee));
                    }
                }
//                array_push($feelist, array('name'=>'全款','fee'=>$config['yukuan']));
//                if ($config['joinfee'] != '0.00' && !empty($config['joinfee'])) {
//                    array_push($feelist, array('name' => '补差价', 'fee' => $config['yukuan'] - $config['joinfee']));
//                } elseif ($config['groupprice'] != '0.00' && !empty($config['groupprice'])) {
//                    array_push($feelist, array('name' => '补差价', 'fee' => $config['yukuan'] - $config['groupprice']));
//                } elseif ($config['primeprice'] != '0.00' && !empty($config['primeprice'])) {
//                    array_push($feelist, array('name' => '补差价', 'fee' => $config['yukuan'] - $config['primeprice']));
//                }
            }
        }
        if (empty($feelist)){
//            return array('error' =>1 , 'msg' => "此活动没有配置线上收款" );
            array_push($feelist, array('name'=>'免费报名','fee'=>0));
        }

        foreach ($feelist as $index => $item) {
            $feelist[$index]['fullname']=$item['name'].":".$item['fee'];
        }

        $confignew = Theme::format_type_config($confignew);
        $result=array();
        $result['op']=$op;
        $result['config']=$confignew;
        $result['feelist'] = $feelist;

        if ($op=="getinfo"){
            if (empty($record['uid']) && strpos($record['avatar'],'yixuansoft.cn')===false){
                $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;
                $qrimg = Poster::CreateScene($system,$scene,$config,'Worker/pages/w_input/w_input');
            }else{
                $qrimg = $record['avatar'];
            }
            $result['qrimg']=$qrimg;
            $result['username']=$record['username'];
            $result['mobile']=$record['mobile'];
            //格式化文本5 多选分类
            if ($config['shopstype']==8){
                $tmp_options = $confignew['options'];
                $tmp_record_options = explode('|',$record['option']);
                if ($tmp_record_options){
                    foreach ($tmp_options as $k => $v){
                        $v_list = $v['list'];
                        foreach ($v_list as $k1 =>$v1){
                            foreach ($tmp_record_options as $kk => $vv){
                                if ($vv==$v1['name']){
                                    $tmp_options[$k]['list'][$k1]['checked']=true;
                                }
                            }
                        }
                    }
                    $result['config']['options']=$tmp_options;
                }
            }
        }
        $result['record']=$record;
        $result['level']=$myworker['level'];
        $result['member_from']=array('未标记','老客户','新客户','微信转帐','店内付款');
        return $result;
    }elseif ($op == 'save') {
        $username = $_P['username'];
        $mobile = $_P['mobile'];
        $realfee = $_P['realfee'];
        $payname = $_P['payname'];

        if (empty($username) || empty($mobile)) {
            return array('error' =>1 , 'msg' => "客户姓名与电话不可为空" );
        }

        if (empty($realfee) || $realfee == "0.00"){
            if ($config['joinfee'] != "0.00"){
                $realfee=$config['joinfee'];
            }elseif ($config['groupprice'] != "0.00"){
                $realfee=$config['groupprice'];
            }else{
                $realfee=$config['primeprice'];
            }
        }
        if ($payname == "拼团价②" && $config['groupprice2'] != '0.00' && !empty($config['groupprice2']) && $realfee==$config['groupprice2']){
            $renshu = 1;
        }elseif ($payname == "拼团价③" && $config['groupprice3'] != '0.00' && !empty($config['groupprice3']) && $realfee==$config['groupprice3']){
            $renshu = 2;
        }else{
            $renshu = 0;
        }
        if ($payname == "单买价" && $config['primeprice'] != '0.00' && !empty($config['primeprice']) && $realfee==$config['primeprice']){
            $paytype = 9;
        }else{
            $paytype = 0;
        }
        if ($system['ruanjian']==5){
            $paytype = 20;
        }
        $pid = 0;
        //如果到了大卡补款时间录的线下定单，如果手机号码在补款之前有定单则视为补款定单；
        if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']) {
            $userlist = db_find("SELECT pid FROM " . tablename(t_record) ." where themeid ='{$themeid}' and status>0 and addtime<'{$config['yukuantime']}' and mobile = '{$mobile}'");
            if (!empty($userlist)){
                $paytype = 8;
                $pid = $userlist['pid'];
            }
        }

        $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
        $data = array(
            'uniacid'  => $_G['mpid'],
            'themeid'  => $themeid,
            'openid'   => '',
            'uid'      => '',
            'nickname' => '',
            'avatar'   => '',
            'username' => $username,
            'mobile'   => $mobile,
            'addtime'  => TIMESTAMP,
            'fee'      => $realfee,
            'option' => $_P['option']=='undefined'?'':trim($_P['option']),
            'address' => $_P['address']=='undefined'?'':trim($_P['address']),
            'formtwo' => $_P['formtwo']=='undefined'?'':trim($_P['formtwo']),
            'datetime' => $_P['datetime']=='undefined'?'':trim($_P['datetime']),
            'addinfo' => $_P['addinfo']=='undefined'?'':trim($_P['addinfo']),
            'member_beizhu' => $_P['member_beizhu']=='undefined'?$record['member_beizhu']:$_P['member_beizhu'],
            'code'     => '',
            'uncode'   => $uncode,
            'status'   => 3,
            'fromuid'  => $_G['member']['uid'],
            'fopenid'  => $_G['openid'],
            'workerid'  => $_G['member']['uid'],
            'pid'      => $pid,
            'type'     => $paytype,
            'tuannum' =>1,
            'renshu'     => $renshu,
            'chongzhi' => $_P['chongzhi']=='undefined'?0:floatval($_P['chongzhi']),
            'member_beizhu' => $_P['member_beizhu']=='undefined'?'':$_P['member_beizhu'],
            'is_member' => $_P['is_member']=='undefined'?0:intval($_P['is_member']),
        );
        if ($system['is_multiple_bargain'] == 1){
            $data['products_id']=intval($_P['products_id']);
        }
        $data = Theme::preg_data($data);

        $res = W_input::check_chongfu($config,$themeid,$username,$mobile);
        if (!empty($res)){
            return array('error' =>1 , 'msg' =>$res);
        }

        Theme::workerreport($themeid,$_G['member']['uid'],array('recordxx' =>1));
        $r = $insertid = db_insert(t_record,$data);


        if(!empty($r)){
            $recordid = $insertid;
            if ($pid==0){
                db_update(t_record,array('pid'=>$recordid),array('id'=>$recordid));
            }
            $scene = MODULE_NAME . "-" . $themeid . "-" . $recordid . "-" . $theme['softkey'] ;

            $qrimg = Poster::CreateScene($system,$scene,$config,'Worker/pages/w_input/w_input');
            // echo $qrimg;
            $data = array(
                'nickname' => '未绑定客户微信',
                'avatar'   => $qrimg,
            );
            $r = db_update(t_record,$data,array("id"=>$recordid));
        }
        $result = array(
            'qrimg' => $qrimg,
            'username' => $username,
            'mobile'   => $mobile,
        );
        $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
                WHERE themeid = :themeid AND id = :id', array(':themeid' => $themeid,':id' => $recordid));
        $result['record']=$record;
        return $result;
    }
}
}